/*
 * @Author: 颜礼田 2564217790@qq.com
 * @Date: 2024-09-07 14:19:53
 * @LastEditors: MrDotYan 2564217790@qq.com
 * @LastEditTime: 2024-09-12 09:41:12
 * @FilePath: /webServer/src/controller/auth/auth.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { Body, Controller, Inject, Post } from '@midwayjs/core';
import { UserService } from '../../service/user/user.service';
import { Validate } from '@midwayjs/validate';
import { LoginValidator, StrIdValidator } from '../../validator';
import { isNotEmpty } from '../../utils/isHelper';
import { JwtService } from '../../service/jwt';
import { BadRequestError } from '@midwayjs/core/dist/error/http';

import dayjs = require('dayjs');

@Controller('/auth')
export class AuthController {
  @Inject()
  private readonly userService: UserService;

  @Inject()
  private readonly jwtService: JwtService;

  @Post('/login')
  @Validate()
  async login(@Body() body: LoginValidator) {
    const user = await this.userService.login(body);
    if (isNotEmpty(user)) {
      return { user, accessToken: this.jwtService.signSync({ id: user.id }) };
    }

    throw new BadRequestError('用户名或密码错误');
  }

  @Post('/logout')
  @Validate()
  async logout(@Body() body: StrIdValidator) {
    const user = await this.userService.info(body.id);
    const logoutTime = dayjs().format('YYYY-MM-DD HH:mm:ss');
    const userSaved = await this.userService.save(
      Object.assign(user, { lastLogoutTime: logoutTime })
    );
    return isNotEmpty(userSaved);
  }
}
